package team.nmsg.photo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

import team.nmsg.ge.system.util.ServerParams;
import team.nmsg.ge.system.util.SysSpringContext;

public class WxUtil {
	
	private static Logger log = LoggerFactory.getLogger(WxUtil.class);
	
	public static String wx_appID = "wxbb5c48d32ece310e";
	public static String wx_appsecret = "b0422a62dbfdb7e1003a343f900c8901";
	
	public static void init() {
		wx_appID = ServerParams.pros.getProperty("wx_appID");
		wx_appsecret = ServerParams.pros.getProperty("wx_appsecret");
	}
	
	private static long expireMinusTime = 3 * 60 *  1000;
	
	private static volatile WXAccessToken wxat = null;
	
	private static volatile WXJSApiTicket jsApiTicket = null;
	
	public static synchronized WXAccessToken getAccess_token() {
		
		if( wxat ==null || isAccessTokenExpire(wxat) ) {
			wxat = getFromWXServer();
		}
		return wxat;
	}
	
	public static synchronized WXJSApiTicket getJsapi_ticket() {
		
		if( jsApiTicket ==null || isJSApiTicketExpire(jsApiTicket) ) {
			jsApiTicket = getAPITicketFromWXServer();
		}
		return jsApiTicket;
	}

	private static WXJSApiTicket getAPITicketFromWXServer() {
		WXJSApiTicket ticket = new WXJSApiTicket();
		RestTemplate template = SysSpringContext.getAppContext().getBean(RestTemplate.class);
		
		WXAccessToken access_token = getAccess_token();
		String wxjsApiTicketURL = getWXJSApiTicketURL(access_token);
		String forObject = template.getForObject(wxjsApiTicketURL, String.class);
		
		for(   int i=0; i<3 ;i++  ) {
			JSONObject parseObject = JSONObject.parseObject(forObject);
			
			log.info( "WXJSApiTicket getAPITicketFromWXServer###"  + parseObject.toJSONString() );
			
			String ticketStr = parseObject.getString("ticket");
			Long expires_in = parseObject.getLong("expires_in");
			int errcode = parseObject.getInteger("errcode");
			String errmsg = parseObject.getString("errmsg");
			if( errcode == 0) {
				long currentTimeMillis = System.currentTimeMillis();
				ticket.setCreateTime(currentTimeMillis);
				ticket.setTicket(ticketStr);
				ticket.setExpire(expires_in);
				return ticket;
			}
			try { Thread.sleep(2000); } catch (InterruptedException e) { 	}
		}
		return null;
	}

	private static boolean isJSApiTicketExpire(WXJSApiTicket jsApiTicket2) {
		long expire = jsApiTicket2.getExpire() * 1000;
		
		long cTime = jsApiTicket2.getCreateTime();
		long nowTime = System.currentTimeMillis();
		
		if(  (nowTime - cTime)>(expire-expireMinusTime)   ) {
			return true;
		}
		
		return false;
	}

	private static boolean isAccessTokenExpire(WXAccessToken wxat2) {
		
		long expire = wxat2.getExpire() * 1000;
		
		long cTime = wxat2.getCreateTime();
		long nowTime = System.currentTimeMillis();
		
		if(  (nowTime - cTime)>(expire-expireMinusTime)   ) {
			return true;
		}
		
		return false;
	}

	private static WXAccessToken getFromWXServer() {
		WXAccessToken tmp = new WXAccessToken();
		
		
		RestTemplate template = SysSpringContext.getAppContext().getBean(RestTemplate.class);
		
		String wxurl = getWXAccessTokenURL();
		String forObject = template.getForObject(wxurl, String.class);
		
		JSONObject parseObject = JSONObject.parseObject(forObject);
		log.info( "WXAccessToken getFromWXServer###"  + parseObject.toJSONString() );
		
		String at = parseObject.getString("access_token");
		Long expires_in = parseObject.getLong("expires_in");
		
		
		long cTime = System.currentTimeMillis();
		tmp.setCreateTime(cTime);
		tmp.setExpire(expires_in);
		tmp.setTokenStr(at);
		
		return tmp;
	}
	
	public static String getWXAccessTokenURL () {
		return "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wx_appID+"&secret="+wx_appsecret;
	}
	
	public static String getWXJSApiTicketURL (WXAccessToken token ) {
		String tokenStr = token.getTokenStr();
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+tokenStr+"&type=jsapi"; 
		return url;
	}

	public static JSONObject signForShareUrl(String shareUrl) {
		WXJSApiTicket jsapi_ticket = getJsapi_ticket();
		String ticket = jsapi_ticket.getTicket();
		
		JSApiSignature jsApiSignature = new JSApiSignature(ticket, shareUrl);
		JSONObject doSignature = jsApiSignature.doSignature();
		
		return doSignature;
	}
	
}
